<template>
  <view class="container">
    <!--
      <block v-for="item in list">
      <neo-tree-list-item
        :paramData="item"
        layer="0"
        @tapTitle="tapTitle"
      ></neo-tree-list-item>
    </block>   
  -->
    <u-empty v-if="list == null || list.length == 0" />

    <view v-else class="layout" style="display: flex; height: 100%">
      <!-- 左边 -->
      <view class="left" style="height: 100%; overflow-y: scroll">
        <view
          style="padding: 15rpx 0"
          v-for="(item, index) in list"
          :key="item.id"
        >
          <view class="fold" style="padding: 15rpx 15rpx 15rpx 0">
            <view
              class=""
              v-show="item.fold && item.children.length > 0"
              @click="unfold(index)"
            >
              <u-icon name="arrow-down" size="20"></u-icon>
            </view>
            <view
              @click="unfold(index)"
              class="tree-icon"
              v-show="!item.fold && item.children.length > 0"
            >
              <u-icon name="arrow-right" size="20"></u-icon>
            </view>
            <view
              :style="{
                paddingLeft: item.children.length == 0 ? '20px' : '0px',
              }"
              @click="onItemClick(item)"
            >
              {{ item.name }}
            </view>
          </view>

          <view
            class="subtree"
            v-if="item.fold"
            v-for="(item1, index1) in item.children"
            :key="item1.id"
            style="display: flex; padding: 15rpx 15rpx 15rpx 0"
          >
            <!-- @click="foldChildren(index, index1)" -->
            <view
              class="tree-content"
              style="padding-left: 30px; padding-right: 20rpx"
              @click="onItemClick(item1)"
            >
              <text>{{ item1.name }}</text>
            </view>

            <view
              class="fold1"
              v-for="(item2, index2) in item1.children"
              :key="item2.id"
              v-if="item1.fold"
            >
              <view class="tree1">
                <u-icon
                  class="icon-children"
                  name="minus-circle"
                  size="24.5px"
                  color="#C0C0C0"
                ></u-icon>
              </view>
              <view @click="onItemClick(item2)">
                <text>{{ item2.title }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      <!-- 右边 -->
      <view
        class="right"
        style="
          flex: 1;
          border-left: 1px solid #e3e3e3;
          padding: 20rpx 20rpx 90rpx;
        "
      >
        <uni-forms ref="form">
          <uni-forms-item class="form-item" label="菜单分类名称:" name="name">
            <view class="lbl">菜单分类名称:</view>
            <uni-easyinput
              :disabled="disabled"
              class="form-item-right"
              type="text"
              placeholder="请填写菜单分类名称"
              v-model="details.name"
            />
          </uni-forms-item>
          <uni-forms-item class="form-item" label="上级分类" name="parentId">
            <view class="lbl">上级分类:</view>
            <picker
              :disabled="disabled"
              class="form-item-right"
              style="flex: 1"
              @change="bindPicker1Change"
              v-model="details.parentId"
              :range="FoodCategoryEnum"
              :range-key="'name'"
            >
              <view class="uni-input">
                {{
                  FoodCategoryEnum.find(
                    (item) => item.id == details.parentId
                  ) == null
                    ? "无"
                    : FoodCategoryEnum.find(
                        (item) => item.id == details.parentId
                      ).name
                }}
              </view>
            </picker>
          </uni-forms-item>
          <uni-forms-item
            class="form-item"
            label="手机点餐端展示"
            name="currencyFlag"
          >
            <view class="lbl">手机点餐端展示:</view>
            <radio-group
              :disabled="disabled"
              class="form-item-right"
              name="appletShow"
            >
              <label style="margin-right: 30rpx">
                <radio
                  :disabled="disabled"
                  :value="1"
                  :checked="details.appletShow == 1"
                />
                <text>是</text>
              </label>
              <label>
                <radio
                  :disabled="disabled"
                  :value="0"
                  :checked="details.appletShow !== 1"
                />
                <text>否</text>
              </label>
            </radio-group>
          </uni-forms-item>

          <!-- 菜单分类别名 -->
          <uni-forms-item class="form-item" label="菜单分类别名" name="byName">
            <view class="lbl">菜单分类别名:</view>
            <uni-easyinput
              :disabled="disabled"
              class="form-item-right"
              type="text"
              v-model="details.byName"
              placeholder="请填写菜单分类别名"
            />
          </uni-forms-item>

          <!-- 分类助记码 -->
          <uni-forms-item class="form-item" label="分类助记码" name="helpCode">
            <view class="lbl">分类助记码:</view>
            <uni-easyinput
              :disabled="disabled"
              class="form-item-right"
              type="text"
              v-model="details.helpCode"
              placeholder="请填写分类助记码"
            />
          </uni-forms-item>
          <!-- 出品部门 -->
          <uni-forms-item class="form-item" label="出品部门" name="departId">
            <view class="lbl">出品部门：</view>
            <picker
              :disabled="disabled"
              class="form-item-right"
              style="flex: 1"
              @change="bindPickerDepartChange"
              v-model="details.departId"
              :range="departmentList"
              :range-key="'name'"
            >
              <view class="uni-input">
                {{
                  departmentList.find((item) => item.id == details.departId) ==
                  null
                    ? "无"
                    : departmentList.find((item) => item.id == details.departId)
                        .name
                }}
              </view>
            </picker>
          </uni-forms-item>
          <uni-forms-item class="form-item" label="排序" name="sort">
            <view class="lbl">排序:</view>
            <uni-easyinput
              :disabled="disabled"
              class="form-item-right"
              type="number"
              v-model="details.sort"
            />
          </uni-forms-item>
        </uni-forms>
        <view class="btn-group">
          <button
            v-if="disabled == true && details !== null"
            style="background-color: #f3c45d; color: #fff"
            size="mini"
            @click="btnDel"
          >
            删除
          </button>
          <button
            v-if="details !== null && disabled == true"
            @click="btnEditClick"
            style="background-color: #f3c45d; color: #fff"
            size="mini"
          >
            编辑
          </button>
          <button
            v-if="details !== null && disabled == false"
            @click="btnSaveClick"
            style="background-color: #f3c45d; color: #fff"
            size="mini"
          >
            保存
          </button>
        </view>
      </view>
    </view>

    <uni-fab
      ref="fab"
      :pattern="pattern"
      :popMenu="false"
      horizontal="right"
      @fabClick="fabClick"
    />
  </view>
</template>

<script>
import { corpId, storeId } from "../../../constants/apiConstants";
import { toastIconEnum } from "../../../constants/uiConstants";
import { umodal, utoast } from "../../../utils/uniUtils.js";
import { isIntegerOrNumericStringOrEmpty } from "../../../utils/stringUtils.js";
import {
  reactive,
  onMounted,
  toRefs,
  getCurrentInstance,
} from "@vue/composition-api";

export default {
  name: "foodcategorylist",
  components: {},
  setup() {
    // 生命周期
    onMounted(async () => {
      await GetDepartment();
      await GetFoodCategory();
    });

    const { proxy } = getCurrentInstance();

    // 数据定义
    const data = reactive({
      departmentList: [],
      pattern: {
        buttonColor: "#F3C45D",
      },
      show: false, // 是否显示弹窗
      canView: false, // 是否显示查看弹窗
      type: "add", // 弹窗类型  1.add 添加  2.edit  编辑
      form: {
        // 表单
        id: 99999999,
        corpId: corpId,
        isDelete: false,
        storeId: storeId,
        name: "",
        createTime: "2199-12-12 00:00:00",
        modifyTime: 0,
      },
      list: [], // 数据源
      viewItem: {}, // 查看的数据
      details: {}, // 当前显示的菜品分类
      disabled: true,
      FoodCategoryEnum: [
        {
          id: 0,
          name: "无上级分类",
        },
      ],
    });

    /**
     * 添加按钮添加事件
     */
    function fabClick() {
      uni.navigateTo({
        url: "/pages/workbench/foodcategory/doAdd",
      });
    }

    function open() {
      data.show = true;
      // console.log('open');
    }

    function close() {
      data.show = false;
      // console.log('close');
    }

    function viewOpen() {
      data.canView = true;
      // console.log('open');
    }

    function viewClose() {
      data.canView = false;
      // console.log('close');
    }

    
    async function btnDelClick(id) {
      if (await umodal()) {
        const res = await DelFoodCategory({ id });
        if (res.code == 0) {
          await utoast(res.msg);
          GetFoodCategory();
        } else {
          await utoast(res.msg);
        }
      }
    }

    /**
     * 编辑按钮点击事件
     * @param item
     */
    async function btnEditClick(item) {
      data.disabled = false;
    }

    /**
     * 查
     */
    async function GetFoodCategory() {
      let {
        data: { list },
      } = await proxy.$api.GetFoodCategory({
        pageNum: 1,
        pageSize: 9999,
      });
      console.log("list-->", list);
      list.forEach((element) => {
        element.label = element.name;
        element.fold = false;
        if (element.children.length > 0) {
          element.children.map((item) => {
            item.label = item.name;
            item.fold = false;
          });
        }
      });

      data.list = list;
      if (list.length > 0) {
        data.details = list[0];
      }
    }

    /**
     * 获取部门列表
     */
    const GetDepartment = async () => {
      let {
        data: { list },
      } = await proxy.$api.GetDepartment({
        pageNum: 1,
        pageSize: 9999,
      });
      console.log("部门列表-->", list);
      data.departmentList = list;
    };

    /**
     * 删
     */
    async function DelFoodCategory() {
      await proxy.$api.DelFoodCategory({
        id: data.details.id,
      });
    }

    /**
     * 改
     * @returns {Promise<void>}
     * @constructor
     */
    async function EditFoodCategory() {
      return await proxy.$api.EditFoodCategory(data.details);
    }

    function unfold(index) {
      console.log(index);
      data.list[index].fold = !data.list[index].fold;
    }

    function foldChildren(index, index1) {
      data.list[index].children[index1].fold =
        !data.list[index].children[index1].fold;
    }

    /**
     *
     * @param item 折叠菜单点击事件
     */
    function onItemClick(item) {
      console.log("item==>", item);
      if (item.id != data.details.id) {
        data.disabled = true;
      }
      if (item.parentId == 0) {
        data.FoodCategoryEnum = [
          {
            id: 0,
            name: "无上级分类",
          },
        ];
      } else {
        data.FoodCategoryEnum = data.list;
      }
      data.details = item;
    }

    
    async function btnDel() {
      if (details.children.length > 0) {
        await utoast("请先删除子项！", toastIconEnum.error);
        return;
      }
      const res = await umodal();
      // 确定删除
      if (res) {
        const result = await DelFoodCategory();
        await utoast("删除成功！");
        await GetFoodCategory();
      }
    }

    /**
     *保存按钮点击事件
     */
    async function btnSaveClick() {
      console.log("提交表单", data.details);
      data.details.name = data.details.name.trim();
      data.details.byName = data.details.byName.trim();
      data.details.helpCode = data.details.helpCode.trim();

      if (data.details.name.length == 0) {
        utoast("名称为空！！", "error");
        return;
      }

      if (data.details.byName.length == 0) {
        utoast("分类别名为空！", "error");
        return;
      }

      if (data.details.helpCode.length == 0) {
        utoast("助记码为空！", "error");
        return;
      }

      if (data.details.sort == null) {
        data.details.sort == 0;
      }

      if (!isIntegerOrNumericStringOrEmpty(data.details.sort)) {
        utoast("排序必须为数字", "error");
        return;
      }

      const res = await EditFoodCategory();
      if (res?.code == 0) {
        utoast("操作成功");
        setTimeout(async () => {
          uni.hideToast();
          data.disabled = true;
          await GetFoodCategory();
        }, 2000);
      } else {
        setTimeout(() => {
          console.log("fail", data.lock);
        }, 2000);
      }
    }

    const bindPickerDepartChange = (e) => {
      data.details.departId = data.departmentList[e.detail.value].id;
      // console.log(e, "e", data.details);
    };

    const bindPicker1Change = (e) => {
      // console.log("e-->", e);
      data.details.parentId = data.FoodCategoryEnum[e.detail.value].id;
    };

    return {
      ...toRefs(data),
      fabClick,
      btnEditClick,
      btnDelClick,
      close,
      open,
      viewClose,
      viewOpen,
      unfold,
      foldChildren,
      onItemClick,
      btnDel,
      btnSaveClick,
      bindPickerDepartChange,
      bindPicker1Change,
    };
  },
};
</script>

<style lang="scss" scoped>
.container {
  overflow-y: scroll;

  .form-item {
    display: flex;
    align-items: center;
    padding: 14rpx 0;

    .lbl {
      width: 80px;
      font-size: 14px;
    }

    .form-item-right {
      flex: 1;
    }
  }

  .img {
    width: 20px;
    height: 20px;
  }
  
  .fold {
    display: flex;
  }

  .btn-group {
    display: flex;
    justify-content: space-around;
    padding-top: 22rpx;
  }
}
</style>
